package io.cw.service.impl.iml.background;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.cw.dao.background.UserInfoDao;
import io.cw.entity.background.UserInfoEntity;
import io.cw.service.impl.background.UserInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;


/**
 * 用户信息服务类 服务类
 *
 * @author cw
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoDao, UserInfoEntity> implements UserInfoService {


    @Override
    public void add(UserInfoEntity dto) {
        this.save(dto.setId(IdWorker.getIdStr())
                     .setCreditScore(100)
                     .setIsValid(1)
        );
    }


    @Override
    public void editCreditScore(String uId, Integer score) {
        UserInfoEntity userInfo = this.lambdaQuery().eq(UserInfoEntity::getIsValid, 1)
                                                    .eq(UserInfoEntity::getId, uId)
                                                    .one();
        if (Objects.isNull(userInfo)) return;

        userInfo.setId(uId).setCreditScore(score);
        this.updateById(userInfo);
    }


    @Override
    public List<UserInfoEntity> findAllUser() {
        return this.lambdaQuery().eq(UserInfoEntity::getIsValid, 1)
                                 .orderByDesc(UserInfoEntity::getId)
                                 .list();
    }

    @Override
    @Transactional
    public void subtractScore(String phoneNumber, int subtractScore) {
        UserInfoEntity userInfo = this.lambdaQuery().eq(UserInfoEntity::getIsValid, 1).eq(UserInfoEntity::getPhoneNumber, phoneNumber).one();
        if (Objects.nonNull(userInfo)){
            userInfo.setCreditScore(userInfo.getCreditScore()-subtractScore);
            this.updateById(userInfo);
        }
    }
}
